package com.xixiake.utils;

import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

/**
 * 创建gson工具类，可使int类型值转为boolean，对加了注解的JavaBean进行值解析
 * Created by c-wanghengli on 2017/5/7.
 */
public class CommonUtil {

    public static GsonBuilder createBuilder(){

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Boolean.class,typeAdapter);
        gsonBuilder.registerTypeAdapter(boolean.class,typeAdapter);
        gsonBuilder.excludeFieldsWithoutExposeAnnotation();
       return gsonBuilder;
    }

    private final static TypeAdapter<Boolean> typeAdapter = new TypeAdapter<Boolean>() {
        @Override
        public void write(JsonWriter out, Boolean value) throws IOException {
            if(null == value){
                out.nullValue();
            }else{
                out.value(value ? 1:0);
            }
        }

        @Override
        public Boolean read(JsonReader in) throws IOException {
            JsonToken peek = in.peek();
            switch (peek){
                case BOOLEAN:
                    return in.nextBoolean();
                case NULL:
                    in.nextNull();
                    return null;
                case NUMBER:
                    return in.nextInt() != 0;
                case STRING:
                    return Boolean.parseBoolean(in.nextString());
                default:
                    throw new IllegalStateException("Expected BOOLEAN or NUMBER but was " + peek);

            }
        }
    };
}
